<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="author" content="lijinbo" />
    <meta name="cdnload" content="mockjs" />
    <title>151-手风琴动画效果</title>
    <style>
      button.accordion {
        background-color: #eee;
        color: #444;
        cursor: pointer;
        padding: 18px;
        width: 100%;
        border: none;
        text-align: left;
        outline: none;
        font-size: 15px;
        transition: 0.4s;
      }

      button.accordion.active,
      button.accordion:hover {
        background-color: #ddd;
      }

      button.accordion:after {
        content: '\002B';
        color: #777;
        font-weight: bold;
        float: right;
        margin-left: 5px;
      }

      button.accordion.active:after {
        content: '\2212';
      }

      div.panel {
        padding: 0 18px;
        background-color: white;
        /** 最大高度的过渡效果 */
        max-height: 0;
        overflow: hidden;
        transition: max-height 0.2s ease-out;
      }
    </style>
  </head>

  <body>
    <div id="max"></div>

    <script>
      // 创建 dom
      const list = Mock.mock({
        'data|5': [{ title: '@ctitle()', content: '@cparagraph(1,10)' }]
      }).data
      const max = document.getElementById('max')
      max.innerHTML = list.reduce((p, c) => {
        p += `
        <button class="accordion">${c.title}</button>
        <div class="panel"><p>${c.content}</p></div>
        `
        return p
      }, '')
      // 添加点击事件
      const btnList = document.querySelectorAll('.accordion')
      btnList.forEach((item) => {
        item.onclick = function () {
          this.classList.toggle('active')
          var panel = this.nextElementSibling
          if (panel.style.maxHeight) {
            panel.style.maxHeight = null
          } else {
            panel.style.maxHeight = panel.scrollHeight + 'px'
          }
        }
      })
    </script>
  </body>
</html>
